package config

import (
	"fmt"
	"log"

	"github.com/spf13/viper"
)

type ServerConfig struct {
	Port int `mapstructure:"port"`
}

type MySQLConfig struct {
	Host     string `mapstructure:"host"`
	Port     int    `mapstructure:"port"`
	User     string `mapstructure:"user"`
	Password string `mapstructure:"password"`
	DBName   string `mapstructure:"dbname"`
	Charset  string `mapstructure:"charset"`
}

type SQLiteConfig struct {
	DBPath string `mapstructure:"db_path"`
}

type AppConfig struct {
	Server ServerConfig `mapstructure:"server"`
	MySQL  MySQLConfig  `mapstructure:"mysql"`
	SQLite SQLiteConfig `mapstructure:"sqlite"`
	DBType string       `mapstructure:"db_type"` // "mysql" or "sqlite"
}

var Cfg AppConfig

func Load() {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")
	viper.AddConfigPath("./config")

	// defaults
	viper.SetDefault("server.port", 8080)
	viper.SetDefault("db_type", "sqlite") // 默认使用SQLite

	// MySQL defaults
	viper.SetDefault("mysql.host", "127.0.0.1")
	viper.SetDefault("mysql.port", 3306)
	viper.SetDefault("mysql.user", "root")
	viper.SetDefault("mysql.password", "luojianfeng")
	viper.SetDefault("mysql.dbname", "erp")
	viper.SetDefault("mysql.charset", "utf8mb4")

	// SQLite defaults
	viper.SetDefault("sqlite.db_path", "./erp.db")

	viper.AutomaticEnv()
	viper.SetEnvPrefix("ERP")

	if err := viper.ReadInConfig(); err != nil {
		log.Printf("config: using defaults/env (no config file): %v", err)
	}
	if err := viper.Unmarshal(&Cfg); err != nil {
		panic(fmt.Errorf("config: unmarshal failed: %w", err))
	}
}

func BuildDSN() string {
	if Cfg.DBType == "sqlite" {
		return Cfg.SQLite.DBPath
	}

	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
		Cfg.MySQL.User,
		Cfg.MySQL.Password,
		Cfg.MySQL.Host,
		Cfg.MySQL.Port,
		Cfg.MySQL.DBName,
		Cfg.MySQL.Charset,
	)
}

func GetDBType() string {
	return Cfg.DBType
}
